/*
 * Copyright (c) 2019 Wormpex.com. All Rights Reserved.
 */

package com.sk.classload;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author ke.su date: 2019-11-19 Time: 下午8:49
 */
public class MyClassLoaderTest extends ClassLoader {

    private String fileExtend = ".class";

    private String path = "/Users/suke/Desktop/";


    public static void main(String[] args) throws Exception {

        MyClassLoaderTest myClassLoaderTest = new MyClassLoaderTest();
        String name = "com.sk.volat.B";


        Class clazz = myClassLoaderTest.loadClass(name);
        System.out.println(clazz.hashCode());

        Object o = clazz.newInstance();

        System.out.println(clazz.getClassLoader());

        System.out.println(o);

        myClassLoaderTest = null;
        clazz = null;
        o=null;

        System.gc();


        Thread.sleep(100000);

        System.out.println("-------------");

        MyClassLoaderTest myClassLoaderTest2 = new MyClassLoaderTest();

        Class<?> aClass = myClassLoaderTest2.loadClass(name);

        System.out.println(aClass.hashCode());


    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("aaaaaaa");

        byte[] data = this.loadClassData(name);

        return this.defineClass(name, data, 0, data.length);
    }

    public byte[] loadClassData(String name) {

        name = name.replace(".", "/");
        try (InputStream is = new FileInputStream(new File(path + name + fileExtend));
             ByteArrayOutputStream bout = new ByteArrayOutputStream()) {

            int ch = 0;
            while (-1 != (ch = is.read())) {
                bout.write(ch);
            }

            return bout.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}


